<template>
  <div style="background-color: #f0f2f5; padding: 0px;">
    <PageHeader
      :breadcrumb="breadcrumb"
      style="background-color: white; padding: 24px; margin-bottom: 16px;"
    />
    <div style="background-color: white; padding: 24px; padding-top: 0px;">
      <div id="operationButton">
        <a-button
          v-if="canAddMacroOrganization"
          size="large"
          type="primary"
          @click="onAddButtonClick"
        >
          添加
        </a-button>
        &nbsp;
        <a-button
            size="large"
            type="primary"
            @click="onRefresh"
        >
          刷新
        </a-button>
        <a-modal
          v-model:visible="addOrEditDialogVisible"
          :title="addOrEditDialogTitle"
          :width="600"
          :keyboard="false"
          :maskClosable="false"
          :footer="null"
          :destroyOnClose="true"
          centered
        >
          <AddOrEditMacroOrganization
            :url="editUrl"
            @operate-success="onAddOrEditSuccess"
            @operate-failed="closeAddOrEditDialog"
          />
        </a-modal>
      </div>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="data"
        :pagination="{ pageSize: 10 }"
        :scroll="{ x: 240 }"
      >
        <template
          v-if="canEditMacroOrganization || canDeleteMacroOrganization"
          #operation="{ record }"
        >
          <TableOperation
            :canEdit="canEditMacroOrganization"
            :canDelete="canDeleteMacroOrganization"
            @edit="onEdit(record.key)"
            @delete="onDelete(record.key)"
          />
        </template>
        <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
          <div style="padding: 8px">
            <a-input
                :ref="c => (searchInput = c)"
                :placeholder="`查询 ${column.title}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block;"
                @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
                type="primary"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template #icon>
                <SearchOutlined/>
              </template>
              查询
            </a-button>
            <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
              重置
            </a-button>
          </div>
        </template>
        <template #filterIcon="filtered">
          <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }"/>
        </template>
        <template #customRender="{ text, column }">
              <span v-if="searchText && searchedColumn === column.dataIndex">
                <template
                    v-for="(fragment, i) in text
                    .toString()
                    .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
                >
                  <mark
                      v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                      :key="i"
                      class="highlight"
                  >
                    {{ fragment }}
                  </mark>
                  <template v-else>{{ fragment }}</template>
                </template>
              </span>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import PageHeader from '../../Common/PageHeader'
import AddOrEditMacroOrganization from './AddOrEditMacroOrganization'
import TableOperation from '../../Common/TableOperation'
import { message } from 'ant-design-vue'
import {SearchOutlined} from '@ant-design/icons-vue'

const operationColumn = {
  title: '操作',
  dataIndex: 'operation',
  slots: { customRender: 'operation' },
  width: 150,
}

export default {
  name: 'MacroOrganization',
  emits: ['add'],
  components: {
    PageHeader,
    AddOrEditMacroOrganization,
    TableOperation,
    SearchOutlined,
  },
  data() {
    const refreshInterval = 100
    return {
      breadcrumb: [
        { key: 1, title: '性能数据管理' },
        { key: 2, title: '组织形貌' },
        { key: 2, title: '宏观形貌'}
      ],
      data: [],
      loading: false,
      addOrEditDialogVisible: false,
      addOrEditDialogTitle: '',
      editUrl: '',
      canAddMacroOrganization: false,
      canEditMacroOrganization: false,
      canDeleteMacroOrganization: false,
      columns: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      refreshInterval,
    }
  },
  mounted() {
    this.columns = this.getDataColumns()
    this.processPermission()
    this.fetch()
  },
  methods: {
    getDataColumns() {
      return [
        {
          title: '样品名称',
          dataIndex: 'sample_name',
          width: 150,
          key: 'sample_name',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '合金代码',
          dataIndex: 'alloy_code',
          width: 150,
          key: 'alloy_code',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '形态',
          dataIndex: 'sample_form',
          width: 150,
          key: 'sample_form',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '形状',
          dataIndex: 'sample_shape',
          width: 150,
          key: 'sample_shape',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '长',
          dataIndex: 'sample_length',
          width: 150,
          key: 'sample_length',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '宽',
          dataIndex: 'sample_width',
          width: 150,
          key: 'sample_width',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '厚度',
          dataIndex: 'sample_thickness',
          width: 150,
          key: 'sample_thickness',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '直径',
          dataIndex: 'sample_diameter',
          width: 150,
          key: 'sample_diameter',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '颜色',
          dataIndex: 'sample_col',
          width: 150,
          key: 'sample_col',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '光泽度',
          dataIndex: 'sample_gloss',
          width: 150,
          key: 'sample_gloss',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: '粗糙度',
          dataIndex: 'sample_roughness',
          width: 150,
          key: 'sample_roughness',
          slots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) =>
              record.name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                // console.log(this.searchInput);
                this.searchInput.focus();
              }, 0);
            }
          },
        },
      ]
    },
    // 处理权限
    processPermission() {
      this.axios
        .get(
          '/has_permission?permission=property_management.add_macro_organization'
        )
        .then((res) => {
          this.canAddMacroOrganization = res.data.result
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get(
          '/has_permission?permission=property_management.change_macro_organization'
        )
        .then((res) => {
          this.canEditMacroOrganization = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canEditMacroOrganization
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get(
          '/has_permission?permission=property_management.delete_macro_organization'
        )
        .then((res) => {
          // console.log(res.data.result)
          this.canDeleteMacroOrganization = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canDeleteMacroOrganization
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
    },
    // 从后端获取数据
    fetch() {
      this.loading = true
      let updatedData = []
      this.axios
        .get('/property_management/macro_organization/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            updatedData.push({
              key: data[i].url,
                  sample_name: data[i].sample_name,
                  alloy_code: data[i].readable_alloy_code,
                  sample_form: data[i].sample_form,
                  sample_shape: data[i].sample_shape,
                  sample_length: data[i].sample_length,
                  sample_width: data[i].sample_width,
                  sample_thickness: data[i].sample_thickness,
                  sample_diameter: data[i]. sample_diameter,
                  sample_col: data[i].sample_col,
                  sample_gloss: data[i].sample_gloss,
                  sample_roughness: data[i].sample_roughness,
            })
          }
          setTimeout(() => {
            this.data = updatedData
            this.loading = false
          }, this.refreshInterval)
          // this.loading = false
          // console.log('chemical:', res)
        })
        .catch((error) => {
          setTimeout(() => {
            this.loading = false
          }, this.refreshInterval)
          console.log('Error', error.message)
        })
    },
    onAddButtonClick() {
      this.addOrEditDialogTitle = '添加宏观形貌'
      this.editUrl = ''
      this.addOrEditDialogVisible = true
      // this.$emit('add')
    },
    onAddOrEditSuccess() {
      this.closeAddOrEditDialog()
      this.fetch()
    },
    closeAddOrEditDialog() {
      this.addOrEditDialogVisible = false
      this.fetch()
    },
    onEdit(key) {
      this.addOrEditDialogTitle = '编辑宏观形貌'
      // console.log(key)
      this.editUrl = key
      this.addOrEditDialogVisible = true
    },
    onDelete(key) {
      message.loading({ content: '删除中...', key })
      const data = [...this.data]
      this.axios
        .delete(key)
        .then(() => {
          setTimeout(() => {
            message.success({ content: '删除成功！', key, duration: 2 })
            this.data = data.filter((item) => item.key !== key)
          }, 1000)
        })
        .catch((error) => {
          setTimeout(() => {
            message.error({ content: '删除失败！', key, duration: 2 })
          }, 1000)
          console.log('Error', error.message)
        })
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      // console.log(selectedKeys[0]);
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
      // this.$forceUpdate();
    },
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
    },
    onRefresh() {
      this.fetch()
    },
  },
}
</script>

<style>
#operationButton {
  text-align: right;
}
</style>
